package com.atguigu.tingshu.search.listener;

import com.atguigu.tingshu.search.service.ItemService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/***
 * 监听订单购买后专辑的购买次数同步消息
 */
@Component
@Log4j2
public class SearchPaidMessageListener {

    @Autowired
    private ItemService itemService;

    /***
     * 订单支付完成以后记录消费信息
     * @param channel
     * @param message
     */
    @RabbitListener(queues = "order_paid_search_queue")
    @SneakyThrows
    public void albumPaidMessageListener(Channel channel, Message message){
        //获取消息
        String orderNo = new String(message.getBody());
        //获取消息的属性
        MessageProperties messageProperties = message.getMessageProperties();
        //获取消息的编号: 当前消费者消费的第几条消息
        long deliveryTag = messageProperties.getDeliveryTag();
        try {
            //增加es中的专辑统计数据
            itemService.updateAlbum(orderNo);
            //确认消息: 1.消息的编号 2.是否批量确认
            channel.basicAck(deliveryTag, false);
        }catch (Exception e){
            //消费消息失败,重新消费
            if(messageProperties.getRedelivered()){
                //将消息丢掉
                channel.basicReject(deliveryTag, false);
            }else{
                //消息没有被拒绝过,第一次: 1.消息的编号 2.是否放回队列
                channel.basicReject(deliveryTag, true);
            }
        }
    }
}
